<template>
  <div class="line-chart" ref="chart" :style="{ width: width, height: height }"></div>
</template>

<script>
  import * as echarts from 'echarts'
  import {
    debounce
  } from 'lodash'

  export default {
    name: 'LineChart',
    props: {
      chartData: {
        type: Array,
        required: true
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '300px'
      },
      color: {
        type: Array,
        default: () =>  ['#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC']
      }
    },
    data() {
      return {
        chart: null
      }
    },
    watch: {
      chartData: {
        deep: true,
        handler() {
          this.updateChart()
        }
      }
    },
    mounted() {
      this.initChart()
      window.addEventListener('resize', this.handleResize)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
      if (this.chart) {
        this.chart.dispose()
      }
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$refs.chart)
        this.updateChart()
      },
      updateChart() {
        // 准备x轴数据（假设是时间点或序号）
       const xAxisData = this.chartData.length>0&&this.chartData[0].dates;
        // 准备系列数据
        const series = this.chartData.map(item => ({
          name: `${item.name}`,
          skuName:`${item.skuName}`,
          type: 'line',
          data: item.velocities
        }));
        const option = {
          title: {
            text: '物料Velocity趋势图',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',

          },
          legend: {
            data: series.map(s => s.name),
            bottom: 10,
            type: 'scroll'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: {
            axisLabel: {
              interval: 0, // 强制显示所有标签
              rotate: 10 // 旋转30度防止重叠
            },
            type: 'category',
            boundaryGap: false,
            data: xAxisData
          },
          yAxis: {
            type: 'value',
            name: 'Velocity值'
          },
          series: series
        };
        this.chart.setOption(option)
      },
      handleResize: debounce(function() {
        if (this.chart) {
          this.chart.resize()
        }
      }, 300)
    }
  }
</script>

<style scoped>
  .line-chart {
    width: 100%;
    height: 100%;
  }
</style>
